package com.onenine.app.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import com.alibaba.sdk.android.manager.OssManager;
import com.onenine.app.R;
import com.onenine.app.event.CommentEvent;
import com.onenine.app.event.CommentSubEvent;
import com.onenine.app.event.ImageTransitionEvent;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.event.SpcRefreshEvent;
import com.onenine.app.fragment.PostDetailFragment;
import com.onenine.app.request.AddCommentRequest;
import com.onenine.app.request.AddCommentSubRequest;
import com.onenine.app.request.DynamicDetailRequest;
import com.onenine.app.request.PostDetailRequest;
import com.onenine.app.response.DynamicDetailResponse;
import com.onenine.app.response.PostDetailResponse;
import com.onenine.app.utils.CHelper;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.UrlConfig;
import com.onenine.app.view.CommentInputView;
import com.onenine.app.view.dialog.InfoIncompleteDialog;
import com.onenine.base.base.BaseEventActivity;
import com.onenine.base.okhttp.BaseResponse;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.Toasty;
import com.onenine.chat.listener.OnMenuClickListener;
import com.onenine.chat.model.FileItem;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.chat.view.AudioRecordButton;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.KeyboardUtils;
import com.onenine.common.util.NetworkUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import cn.jzvd.Jzvd;

/**
 * 创建时间：2018/7/12 0012 17:50
 * 创建人：fly
 * 功能描述：帖子详情
 */
public class PostDetailActivity extends BaseEventActivity implements OnMenuClickListener, OssManager.Callback
        , View.OnTouchListener, AudioRecordButton.AudioFinishRecorderListener {

    private PostDetailFragment mDetailFragment;
    private CommentInputView mInputBar;
    private String mPkId;
    private CommentEvent mCommentEvent;
    private CommentSubEvent mCommentSubEvent;
    private int mPostType = DataType.POST_TOPIC;

    @Override
    protected int getLayout() {
        return R.layout.activity_post_detail;
    }

    /**
     * 带id类型和多图排版方式启动
     *
     * @param context
     * @param id
     */
    public static void launchActivity(Context context, String id, int postType, int spanType) {
        Intent intent = new Intent(context, PostDetailActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("postType", postType);
        intent.putExtra("spanType", spanType);
        context.startActivity(intent);
    }

    /**
     * 带id且滑动评论区
     *
     * @param context
     * @param id
     */
    public static void launchCommentActivity(Context context, String id, int postType, int spanType) {
        Intent intent = new Intent(context, PostDetailActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("postType", postType);
        intent.putExtra("spanType", spanType);
        intent.putExtra("comment", true);
        context.startActivity(intent);
    }

    /**
     * 获取带id和类型意图
     *
     * @param id
     * @param postType
     * @return
     */
    public static Intent getPenddingIntent(String id, int postType) {
        Intent intent = new Intent(ApUtils.getApp(), PostDetailActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("postType", postType);
        return intent;
    }

    @Override
    protected void initViews() {
        super.initViews();
        mPkId = getIntent().getStringExtra("id");
        mInputBar = findViewById(R.id.input_view);
        mInputBar.setAudioFormat(false);
        mDetailFragment = (PostDetailFragment) getFragmentManager()
                .findFragmentById(R.id.frag_topic_reply);
        mToolbar.setCenterTitle(R.string.detail);
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        mInputBar.setMenuClickListener(this);
        mDetailFragment.getView().setOnTouchListener(this);
        mInputBar.getRecordVoiceButton().setAudioFinishRecorderListener(this);
    }

    @Override
    protected void initData() {
        super.initData();
        mPostType = getIntent()
                .getIntExtra("postType", DataType.POST_TOPIC);
        if (mPostType == DataType.POST_DYNAMIC) {
            getDynamicDetail();
        } else {
            getTopicDetail();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }

    /**
     * 获取动态详情
     */
    private void getDynamicDetail() {
        showLoading();
        DynamicDetailRequest request = new DynamicDetailRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setDynamickPkId(mPkId);
        OkRequest.getInstance().withUrl(UrlConfig.DYNAMIC_DETAIL).withRequest(request)
                .doRequest(PostDetailActivity.class.getSimpleName(), new OkCallback<DynamicDetailResponse>() {
                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onResponse(DynamicDetailResponse response, String srcData) {
                        dismissLoading();
                        if (response.isSuccess()) {
                            if (PostDetailActivity.this.isFinishing()) {
                                return;
                            }
                            createPostCommentEvent(DataType.POST_DYNAMIC);
                            mDetailFragment.bindPostIdType(mPkId, DataType.POST_DYNAMIC)
                                    .bindDynamicDetail(getIntent().getIntExtra("spanType", -1), getIntent()
                                            .getBooleanExtra("comment", false), response).bindTopicComments();
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                    }
                });
    }

    /**
     * 获取帖子详情
     */
    private void getTopicDetail() {
        showLoading();
        PostDetailRequest request = new PostDetailRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setPkId(mPkId);
        OkRequest.getInstance().withUrl(UrlConfig.GET_POST_DETAIL).withRequest(request)
                .doRequest(PostDetailActivity.class.getSimpleName(), new OkCallback<PostDetailResponse>() {
                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onResponse(PostDetailResponse response, String srcData) {
                        dismissLoading();
                        if (response.isSuccess()) {
                            if (PostDetailActivity.this.isFinishing()) {
                                return;
                            }
                            createPostCommentEvent(mPostType);
                            mDetailFragment.bindPostIdType(mPkId, mPostType)
                                    .bindPostDetail(getIntent().getIntExtra("spanType", -1)
                                            , getIntent().getBooleanExtra("comment", false)
                                            , response).bindTopicComments();
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                    }

                });
    }

    /**
     * 创建帖子评论事件
     *
     * @param postType
     */
    private void createPostCommentEvent(int postType) {
        mCommentEvent = new CommentEvent();
        mCommentEvent.foreignPkId = mPkId;
        mCommentEvent.commentType = postType;
    }

    /**
     * 发送评论请求
     *
     * @param request
     */
    private void sendCommentRequest(AddCommentRequest request) {
        OkRequest.getInstance().withUrl(UrlConfig.ADD_POST_COMMENT)
                .withRequest(request)
                .doRequest(getClass().getSimpleName(), new OkCallback<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse response, String srcData) {
                        if (response.isSuccess()) {
                            Toasty.showNormal("评论成功");
                            mInputBar.clearEditText();
                            KeyboardUtils.hideSoftInput(mInputBar);
                            EventBus.getDefault().post(new RefreshEvent(DataType.REFRESH_COMMENT_SUCCESS));
                            EventBus.getDefault().post(new SpcRefreshEvent(mPkId, SpcRefreshEvent.SPC_COMMENT, true));
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                    }
                });
    }

    /**
     * 发送子评论
     *
     * @param request
     */
    private void sendCommentSubRequest(AddCommentSubRequest request) {
        OkRequest.getInstance().withUrl(UrlConfig.ADD_REPLY_COMMENT)
                .withRequest(request)
                .doRequest(getClass().getSimpleName(), new OkCallback<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse response, String srcData) {
                        if (response.isSuccess()) {
                            Toasty.showNormal("回复成功");
                            mInputBar.clearEditText();
                            KeyboardUtils.hideSoftInput(mInputBar);
                            EventBus.getDefault().post(new RefreshEvent(DataType.REFRESH_REPLY_SUCCESS));
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                    }
                });
    }

    @Override
    public void onActivityReenter(int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            //见BrowserImageActivity的共享视图返回
            ImageTransitionEvent event = new ImageTransitionEvent();
            event.position = data.getIntExtra(BrowserImageActivity.IMG_CURRENT_POSITION, -1);
            event.eventName = PostDetailActivity.class.getSimpleName();
            EventBus.getDefault().post(event);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(CommentEvent event) {
        if (CHelper.isLabelInfoImPerfect()) {
            new InfoIncompleteDialog(this).show();
            return;
        }
        mCommentEvent = event;
        mCommentSubEvent = null;
        mInputBar.setEditTextHint("");
        showAutoInputEditText();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(CommentSubEvent event) {
        if (CHelper.isLabelInfoImPerfect()) {
            new InfoIncompleteDialog(this).show();
            return;
        }
        mCommentSubEvent = event;
        mCommentEvent = null;
        mInputBar.setEditTextHint(getString(R.string.reply_sub_comment_hint, event.fromUserName));
        showAutoInputEditText();
    }

    /**
     * 显示输入框
     */
    private void showAutoInputEditText() {
        EditText edt = mInputBar.getInputView();
        edt.requestFocus();
        KeyboardUtils.showSoftInput(edt);
    }

    /**
     * 发送评论或子评论数据
     *
     * @param comment
     * @return
     */
    private boolean sendCommentData(int type, String comment) {
        if (mCommentEvent != null) {
            AddCommentRequest request = new AddCommentRequest();
            request.setUserId(RcUser.getInstance().getUserId());
            request.setcType(type);
            request.setCommentType(mCommentEvent.commentType);
            request.setForeignPkId(mCommentEvent.foreignPkId);
            request.setComment(comment);
            sendCommentRequest(request);
        } else if (mCommentSubEvent != null) {
            AddCommentSubRequest request = new AddCommentSubRequest();
            request.setForeignPkId(mCommentSubEvent.foreignPkId);
            request.setUserId(RcUser.getInstance().getUserId());
            request.setCommentPkId(mCommentSubEvent.commentPkId);
            request.setCommentSubType(mCommentSubEvent.commentSubType);
            request.setTargetUserId(mCommentSubEvent.fromUserId);
            request.setcType(type);
            request.setCommentSubDesc(comment);
            sendCommentSubRequest(request);
        }
        return false;
    }

    @Override
    public void onSendFiles(List<FileItem> list) {

    }

    @Override
    public boolean onSendVoiceMessage() {
        return true;
    }

    @Override
    public boolean onExpandOption(int postion) {
        return false;
    }

    @Override
    public boolean switchToCameraMode() {
        return false;
    }

    @Override
    public boolean switchToEmojiMode() {
        return true;
    }

    @Override
    public boolean switchToExpandMode() {
        return false;
    }

    @Override
    public boolean onSendTextMessage(CharSequence input) {
        if (input == null || input.length() == 0) {
            return false;
        }
        return sendCommentData(DataType.COMMENT_TEXT_TYPE, input.toString());
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        } else if (mInputBar.isEmojiVisible()) {
            mInputBar.dismissMenuLayout();
            mInputBar.dismissEmojiLayout();
            return;
        }
        super.onBackPressed();
    }

    @Override
    public boolean onTouch(View v, MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            if (mInputBar.isKeyboardVisible()) {
                KeyboardUtils.hideSoftInput(PostDetailActivity.this);
            } else if (mInputBar.isEmojiVisible()) {
                mInputBar.dismissEmojiLayout();
            }
            return true;
        }
        return false;
    }

    @Override
    public void onFinished(float seconds, String filePath) {
        if (!NetworkUtils.isConnected()) {
            Toasty.showNormal(R.string.rc_network_exception);
        } else {
            OssManager.getInstance(ApUtils.getApp())
                    .ossUpload(OssManager.VOICE_TYPE, filePath, this);
        }
    }

    @Override
    public void onSuccess(String url) {
        sendCommentData(DataType.COMMENT_VOICE_TYPE, url);
    }

    @Override
    public void onProgress(float progress) {

    }

    @Override
    public void onFailure(int errorCode, String errorMsg) {
        Toasty.showNormal(errorCode);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mInputBar.getRecordVoiceButton()
                .setAudioFinishRecorderListener(null);
    }

}
